<template>
  <div class="configs-container">
    <!-- 操作栏 -->
    <div class="mb-4">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新建配置
      </el-button>
    </div>

    <!-- 配置列表 -->
    <el-card>
      <template #header>
        <span>导入配置列表</span>
      </template>

      <el-table
        :data="configList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="name" label="配置名称" width="200" />
        <el-table-column label="文件类型" width="120">
          <template #default="{ row }">
            <el-tag :type="row.fileType === 'score' ? 'warning' : 'primary'" size="small">
              {{ row.fileType === 'score' ? '比分文件' : '首页文件' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="执行频率" width="120">
           <template #default="{ row }">
             <el-tag 
               :type="row.frequency === 'daily' ? 'success' : row.frequency === 'hourly' ? 'info' : 'warning'" 
               size="small"
             >
               {{ row.frequency === 'daily' ? '每日' : row.frequency === 'hourly' ? '每小时' : '手动' }}
             </el-tag>
           </template>
         </el-table-column>
        <el-table-column prop="importPath" label="导入路径" min-width="200" />
        <el-table-column label="执行时间" width="120">
          <template #default="{ row }">
            {{ formatTime(row.importHour, row.importMinute) }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" />
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.isEnabled ? 'success' : 'danger'">
              {{ row.isEnabled ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTimeDisplay(row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button
              :type="row.isEnabled ? 'warning' : 'success'"
              size="small"
              @click="handleToggleStatus(row)"
            >
              {{ row.isEnabled ? "禁用" : "启用" }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 创建/编辑对话框 -->
    <ConfigDialog
      v-model:visible="dialogVisible"
      :config="currentConfig"
      :is-edit="isEdit"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import {
  getImportConfigs,
  updateImportConfig,
  deleteImportConfig,
  type ImportConfig
} from "@/api/automation";
import ConfigDialog from "./components/ConfigDialog.vue";
// 移除AutomationNav导入，现在由父页面统一管理
import { formatDateTime } from "@/utils/formatTime";

// 响应式数据
const loading = ref(false);
const configList = ref<ImportConfig[]>([]);
const dialogVisible = ref(false);
const currentConfig = ref<ImportConfig | null>(null);
const isEdit = ref(false);

// 格式化时间显示
const formatTime = (hour: number, minute: number) => {
  return `${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}`;
};

// 格式化日期时间
const formatDateTimeDisplay = (dateTime: string) => {
  if (!dateTime) return "-";
  return formatDateTime(new Date(dateTime), "YYYY-MM-DD HH:mm:ss");
};

// 获取配置列表
const fetchConfigs = async () => {
  try {
    loading.value = true;
    const response = await getImportConfigs();
    if (response.code === 0) {
      configList.value = response.data;
    } else {
      ElMessage.error(response.message || '获取配置列表失败');
    }
  } catch (error) {
    console.error("获取配置列表失败:", error);
    ElMessage.error("获取配置列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理新建配置
const handleCreate = () => {
  currentConfig.value = null;
  isEdit.value = false;
  dialogVisible.value = true;
};

// 处理编辑配置
const handleEdit = (config: ImportConfig) => {
  currentConfig.value = { ...config };
  isEdit.value = true;
  dialogVisible.value = true;
};

// 处理切换状态
const handleToggleStatus = async (config: ImportConfig) => {
  try {
    const newStatus = !config.isEnabled;
    const action = newStatus ? "启用" : "禁用";

    await ElMessageBox.confirm(
      `确定要${action}配置"${config.name}"吗？`,
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const updateData = {
      name: config.name,
      importPath: config.importPath,
      fileType: config.fileType || 'homepage',
      frequency: config.frequency || 'daily',
      isEnabled: newStatus,
      description: config.description,
      importHour: config.importHour,
      importMinute: config.importMinute,
      intervalMinutes: config.intervalMinutes,
      maxRetries: config.maxRetries,
      retryIntervalMinutes: config.retryIntervalMinutes
    };

    const response = await updateImportConfig(config.id!, updateData);
    if (response.code === 0) {
      ElMessage.success(`${action}成功`);
      await fetchConfigs();
    } else {
      ElMessage.error(response.message || `${action}失败`);
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("切换状态失败:", error);
      ElMessage.error("操作失败");
    }
  }
};

// 处理删除配置
const handleDelete = async (config: ImportConfig) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除配置"${config.name}"吗？此操作不可恢复。`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await deleteImportConfig(config.id!);
    if (response.code === 0) {
      ElMessage.success('删除成功');
      await fetchConfigs();
    } else {
      ElMessage.error(response.message || '删除失败');
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除配置失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 处理对话框成功事件
const handleDialogSuccess = () => {
  dialogVisible.value = false;
  fetchConfigs();
};

// 组件挂载时获取数据
onMounted(() => {
  fetchConfigs();
});
</script>

<style scoped>
.automation-configs {
  padding: 20px;
}
</style>
